/**
 * 同步阻塞IO Client端的思路：
 * 1 新建一个 Socket 监听指定地址+端口
 * 2 使用 PrintWriter 写入一条命令到 Socket 输出流中
 * 3 使用 BufferReader 读取socket输入流中的来自Server的应答
 *
 * @author chentl
 * @version V1.0
 * @Project leisurely
 * @Title TimeClient.java
 * @Description 时间服务客户端
 * @Package com.echo.ioex.io.client
 * @date 2020/9/15 1:20 下午
 * @Copyright: 陈泰来の学习档案 .
 */
package com.echo.ioex.bio.client;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;


@Slf4j
public class TimeClient {

    public static void main(String[] args) {
        int port = 9999;

        //参数读取
        if (args != null && args.length > 0) {
            try {
                port = Integer.parseInt(args[0]);
            } catch (NumberFormatException e) {
                //端口采用默认值
            }
        }

        Socket socket = null;
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            socket = new Socket("127.0.0.1", port);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);

            out.println("QUERY TIME ORDER");
            log.info("指令:{} 发送成功", "QUERY TIME ORDER");
            String response = in.readLine();
            log.info("收到回应：" + response);
        } catch (Exception e) {
            //无需处理
        } finally {
            //关闭输出流
            if (out != null) {
                out.close();
                out = null;
            }

            //关闭输入流
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                in = null;
            }

            //关闭socket 释放句柄资源
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                socket = null;
            }


        }

    }
}
